<?php

namespace App\Listeners;

use App\Constant\QueueKey;
use App\Events\CollectionReceiptEvent;
use App\Models\CollectionApiRequest;
use App\Models\RepayRecord;
use App\Models\Traits\RepaySummary;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use App\Events\RepayMentEvent;
use App\Events\ActiveDeductionEvent;
use App\Models\RepayRecordCommon;
use App\Models\RepayRecordMoney;
use App\Models\RepayRecordMonth;


class CollectionReceiptListener implements  ShouldQueue{
    use InteractsWithQueue;
    public $connection = 'redis';

    public $queue = QueueKey::QUEUE_COLLECTION_RECEIPT;

    const NOTIFY_TYPE_ONE=1;//代扣申请反馈
    const NOTIFY_TYPE_TWO=2;//销账申请反馈
    const NOTIFY_TYPE_THREE=3;//提前结清反馈

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  CollectionReceiptEvent  $event
     * @return void
     */
    public function handle(CollectionReceiptEvent $event)
    {
        $record_id = $event->record_id;
        $recordInfo = RepayRecord::where('id',$record_id)->first();
        //已经分配的案件进行推送&主动还款的行为记录推送
        $this->sendUpRepay($recordInfo);
        //如果是催收那边发起的,回执一下
//        try{
//            if($recordInfo){
//                //判断类型,只有代扣,销账,全部结清才会调用回执接口
//                switch ($recordInfo->repay_type){
//                    case RepayRecord::REPAY_TYPE_WITHHOLDING:
//                        //代扣
//                        $this->withholdingEvent($recordInfo);
//                        break;
//                    case RepayRecord::REPAY_TYPE_ACCOUNT:
//                        //销账
//                        $this->PayCompensateEvent($recordInfo);
//                        break;
//                    case RepayRecord::REPAY_TYPE_REPAYMENT:
//                        //全部还清
//                        $this->withholdingEvent($recordInfo);
//                        break;
//
//                    default:
//                        $this->withholdingEvent($recordInfo);
//                        break;
//                }
//            }
//        }catch (\Exception $e){
//            \Log::debug($e->getMessage());
//        }
//        return;
    }

    /**
     * Description:接口3:更新已经分配的案件信息&接口5:用户主动还款的行为推送
     * Author:lijiafei
     */
    protected function sendUpRepay($recordInfo){
        //判断是否分配案件
        if($recordInfo->relationSummary->up_type == \App\Models\RepaySummary::UP_TYPE_ZERO){
            return;
        }
        //更新当前的还款记录到催收
        event(new RepayMentEvent($recordInfo->summary_id));//更新已经分配的案件信息
        event(new ActiveDeductionEvent($recordInfo->id));//用户主动还款的行为推送
    }

//    /**
//     * Description:获取请求数据
//     * Author:lijiafei
//     * @param RepayRecord $recordInfo model对象
//     * @param $api_type int api类型
//     * @param $status 1 响应成功 2 回执成功 3部分成功部分失败
//     * @return array
//     */
//    public function sendData(RepayRecord $recordInfo,$api_type,$status){
//        $summaryInfo = \App\Models\Collection\RepaySummary::select(['loan_id','id','data_type','trans_id'])->where('id',$recordInfo->summary_id)->first();
//        $responseData = [
//            'caseCode' => $summaryInfo->getCaseCode(),
//            'type' => $api_type,
//            'applyNumber' => $recordInfo->apply_number,
//            'statue' => $status,
//            'message' =>$recordInfo->status==RepayRecord::STATUS_THREE?$recordInfo->failure_message:'',
//        ];
//        return $responseData;
//    }
//
//    /**
//     * Description:对回执的响应进行处理
//     * Author:lijiafei
//     * @param $collection_id integer collection_api_request表的id
//     * @param $result 回执响应数据
//     */
//    private function saveReceiptData($collection_id,$result){
//        if(isset($result['resultData'])){
//            $receipt_response_code = isset($result['resultData']['result']) ? $result['resultData']['result'] : 0;
//            $updateData = [
//                'receipt_response_code' => $receipt_response_code,
//                'receipt_response_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
//            ];
//            CollectionApiRequest::where('id',$collection_id)->update($updateData);
//            Log::debug('回执接口返回:' . json_encode($result,JSON_UNESCAPED_UNICODE));
//        }
//    }
//
//    protected  function withholdingEvent(RepayRecord $recordInfo){
//        //判断是否回执成功
//        $collectionData = CollectionApiRequest::where('response_code',CollectionApiRequest::RESPONSE_OK)->where('apply_number',$recordInfo['apply_number'])->first();
//        //判断是否回执成功了
//        if($collectionData && $collectionData->status == CollectionApiRequest::STATUS_RECEIPT_OK){
//            \Log::debug('接口回执:全部还清' . ":回执流水号为" . $recordInfo->apply_number . '的回执已经成功,不能重复回执' . Carbon::now()->toDateTimeString());
//            return;
//        }
//
//        $api_type=0;
//        if($recordInfo->repay_type==RepayRecord::REPAY_TYPE_WITHHOLDING){
//            $api_type=self::NOTIFY_TYPE_ONE;
//
//        }elseif($recordInfo->repay_type==RepayRecord::REPAY_TYPE_ACCOUNT){
//            $api_type=self::NOTIFY_TYPE_TWO;
//        }elseif($recordInfo->repay_type==RepayRecord::REPAY_TYPE_REPAYMENT){
//            $api_type=self::NOTIFY_TYPE_THREE;
//        }
//
//        if($recordInfo->repay_type!=RepayRecord::REPAY_TYPE_REPAYMENT){
//            $recordResult=RepayRecord::where('summary_id',$recordInfo->summary_id)
//                ->where('apply_number',$recordInfo->apply_number)
//                ->whereIn('status',[RepayRecord::STATUS_THREE,RepayRecord::STATUS_FOUR])->get();
//            $repayCount=RepayRecord::where('summary_id',$recordInfo->summary_id)
//                ->where('apply_number',$recordInfo->apply_number)
//                ->where('status','!=',1)->count();
//
//        }else{
//            $recordResult=RepayRecord::where('summary_id',$recordInfo->summary_id)
//                ->where('pay_off',RepayRecord::PAY_OFF_TWO)
//                ->where('period','!=',0)
//                ->get();
//            ;
//            $repayCount=RepayRecord::where('summary_id',$recordInfo->summary_id)
//                ->where('pay_off',RepayRecord::PAY_OFF_TWO)->where('period','!=',0)->count()
//            ;
//
//        }
//
//        \Log::debug(['tetsttttt'=>$repayCount==count($recordResult)]);
//
//        //todo 全部执行完毕执行通知逻辑
//        if($repayCount==count($recordResult)){
//            $recordIds=[];//事件通知
//            $periods=[];//成功期限通知
//            $message='';
//            $partSuccessRecorIds=[];//todo 部分成功推送事件id
//            foreach ($recordResult as $key => $record) {
//                $feedBackList[] = [
//                    'periodNumber' => $record->period,
//                    'repayPlanNumber' => $record->relationSummary->data_type==\App\Models\RepaySummary::DATA_TYPE_TWO?$record->repay_plan_number:'K2-' . $record->id . '-' . date('Ymd', strtotime($record->created_at)),
//                    'repayState' => $record->status == RepayRecord::STATUS_FOUR ? 1 : 2,
//                    'repayMessage' => $record->status == RepayRecord::STATUS_FOUR ? '还款成功' : $record->failure_message,
//                   // 'debtMoney'=>RepaySummary::getNotRepayAmount($record),
//                ];
//                if ($record->status == RepayRecord::STATUS_FOUR) {//
//                    $periods[] = $record->period;
//                    $recordIds[] = $record->id;
//                } elseif ($record->status == RepayRecord::STATUS_THREE) {
//                    $message = $record->failure_message;
//                    //todo 部分成功记录推送
//                    if ($record->money->status == RepayRecordMoney::STATUS_FOUR || $record->month->status == RepayRecordMonth::STATUS_FOUR || $record->common->status == RepayRecordCommon::STATUS_FOUR) {
//                        $partSuccessRecorIds[] = $record->id;
//                    }
//                }
//            }
//
//            $pushRecordIds=array_merge($recordIds,$partSuccessRecorIds);
//            if($pushRecordIds){//todo 如果存在成功的通知事件
//                foreach($pushRecordIds as $key=>$pushRecordId){
//                    $event=['summaries'=>$recordInfo->summary_id,'records'=>[$pushRecordId]];
//                    event(new RepayMentEvent($event));
//                    event(new ActiveDeductionEvent($event));
//                }
//            }
//            //todo  等推送对接//推送后结果
//            $sendData=[];
//
//            if(count($periods)==$repayCount){//todo 期限合计等于该期回款，推送成功
//                $sendData=$this->sendData($recordInfo,$api_type,1);
//            }else{//todo 失败或者部分失败
//                if($partSuccessRecorIds){
//                    $sendData=$this->sendData($recordInfo,$api_type,3);
//                }else{
//                    $sendData=$this->sendData($recordInfo,$api_type,2);
//                }
//
//
//            }
//            $sendData['feedBackList']=$feedBackList;
//            \Log::debug('代扣回执成功拉，数据'.(json_encode($sendData)));
//            $result = \CollectionRequest::sendReceipt($sendData);
//            \Log::debug('tets-tianping');
//            $this->saveReceiptData($collectionData->id,$result);
//
//        }
//    }
//
//    public function PayCompensateEvent(RepayRecord $recordInfo)
//    {
//
//        //判断是否回执成功
//        $collectionData = CollectionApiRequest::where('response_code',CollectionApiRequest::RESPONSE_OK)->where('apply_number',$recordInfo['apply_number'])->first();
//        //判断是否回执成功了
//        if($collectionData && $collectionData->status == CollectionApiRequest::STATUS_RECEIPT_OK){
//            \Log::debug('接口回执:销账' . ":回执流水号为" . $recordInfo->apply_number . '的回执已经成功,不能重复回执' . Carbon::now()->toDateTimeString());
//            return;
//        }
//        $recordResult=RepayRecord::where('summary_id',$recordInfo->summary_id)
//            ->where('apply_number',$recordInfo->apply_number)
//            ->whereIn('status',[RepayRecord::STATUS_THREE,RepayRecord::STATUS_FOUR])->get();
//        $repayCount=RepayRecord::where('summary_id',$recordInfo->summary_id)
//            ->where('apply_number',$recordInfo->apply_number)
//            ->where('status','!=',1)->count();
//
//        if($repayCount==count($recordResult)){
//            $recordIds=[];//事件通知
//            $periods=[];//成功期限通知
//            $partSuccessRecordIds=[];
//            foreach($recordResult as $key=>$record){
//                if($record->status==RepayRecord::STATUS_FOUR){//
//                    $recordIds[]=$record->id;
//                    $periods[]=$record->period;
//                }elseif($record->status==RepayRecord::STATUS_THREE){
//                    if($record->money->status==RepayRecordMoney::STATUS_FOUR || $record->month->status==RepayRecordMonth::STATUS_FOUR || $record->common->status==RepayRecordCommon::STATUS_FOUR){
//                        $partSuccessRecordIds[]=$record->id;
//                    }
//                }
//            }
//            $pushRecordIds=array_merge($recordIds,$partSuccessRecordIds);
//            if($pushRecordIds){
//                foreach($pushRecordIds as $key=>$pushRecordId){
//                    $event=['summaries'=>$recordInfo->summary_id,'records'=>[$pushRecordId]];
//                    event(new RepayMentEvent($event));
//                    event(new ActiveDeductionEvent($event));
//                }
//            }
//            if($recordInfo->status==\App\Models\RepayRecord::STATUS_FOUR){
//                $sendData=$this->sendData($recordInfo,self::NOTIFY_TYPE_TWO,1);
//            }elseif($recordInfo->status==\App\Models\RepayRecord::STATUS_THREE){
//                $sendData=$this->sendData($recordInfo,self::NOTIFY_TYPE_TWO,2);
//                if($periods){
//                    $returnArray['period']=$periods;
//                }
//            }else{
//                return ;
//            }
//
//            $result = \CollectionRequest::sendReceipt($sendData);
//            $this->saveReceiptData($collectionData->id,$result);
//        }
//    }

}